package com.tanhua.service;

import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.UserInfoAPI;
import com.tanhua.dubbo.mongo.CommentAPI;
import com.tanhua.mongo.Comment;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentsService {

    @DubboReference
    private CommentAPI commentAPI;

    @DubboReference
    private UserInfoAPI userInfoAPI;


    public PageResult findByPage(String movementId, Integer page, Integer pagesize) {
        //1 远程调用mongo，传入movementId，page，pagesize，查找对应的评论 state=2
        PageResult pr = commentAPI.findByPage(movementId,page,pagesize);
        //2 封装结果
        if (pr.getItems().size()<1){
            return pr;
        }
        List<Comment> items = (List<Comment>) pr.getItems();
        List<CommentVo> commentVoList = new ArrayList<>();
        //3 返回
        for (Comment c:items){
            CommentVo vo = new CommentVo();
            //1 查找用户信息
            UserInfo userInfo = userInfoAPI.findById(c.getUserId());
            BeanUtils.copyProperties(c,vo);
            BeanUtils.copyProperties(userInfo,vo);
            vo.setId(c.getId().toHexString());
            Date date = new Date(c.getCreated());
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            vo.setCreateDate(format);

            commentVoList.add(vo);
        }

        pr.setItems(commentVoList);
        return pr;
    }
}
